// web/src/app/api/(learn)/course/[courseId]/route.ts
import {NextRequest, NextResponse} from "next/server";
import {currentUser} from "@/lib/auth";
import {db} from "@/lib/db";

export async function PATCH(
    req: NextRequest,
    {params}: { params: { courseId: string } }
) {
    try {
        const user = await currentUser()
        const {courseId} = params
        const values = await req.json()

        if (!user) {
            return new NextResponse('Unauthorized', {status: 401})
        }

        const course = await db.course.update({
            where: {
                id: courseId,
                userId: user?.id
            },
            data: {
                ...values
            }
        })

        return NextResponse.json(course)
    } catch (err) {
        console.error('[COURSE_ID]', err)
        return new NextResponse('Internal Error', {status: 500})
    }
}


export async function DELETE(
    req: NextRequest,
    {params}: { params: { courseId: string } }
) {
    try {
        const user = await currentUser()
        const {courseId} = params

        if (!user) {
            return new NextResponse('Unauthorized', {status: 401})
        }

        const course = await db.course.findUnique({
            where: {
                id: courseId,
                userId: user?.id
            },
            include: {
                chapters: {
                    include: {
                        muxData: true
                    }
                }
            }
        })

        if (!course) {
            return new NextResponse('Not Found', {status: 404})
        }

        // for delete remote muxData video

        const deletedCourse=await db.course.delete({
            where: {
                id: courseId,
            }
        })

        return NextResponse.json(deletedCourse)
    } catch (err) {
        console.error('[COURSE_ID_DELETE]', err)
        return new NextResponse('Internal Error', {status: 500})
    }
}